<?php
require_once (__DIR__ . "/../inc/functions.php");

class keywords
{
	static function GetAll()
	{
		$conn = GetConnection();
		$results=$conn->query('SELECT * FROM keywords');
		$error=$conn->error;
		return $results;
	}
	
	static function Get($id)
	{
		$conn = GetConnection();
		$results = $conn->query("SELECT * FROM keywords WHERE id=$id");
		$row = $results->fetch_assoc();
		$error=$conn->error;
		return $row;
	}
	
	static function GetName($id)
	{
		$row = keywords::Get($id);
		return $row['name'];
	}
	
	static function GetChildren($name)
	{
		$conn = GetConnection();
		/* note: NAME has UNIQUE constraint so we know 1 row is returned 	 */
		$results = $conn->query("SELECT * FROM keywords WHERE name='$name'");
		$row = $results->fetch_assoc();  
		/* use name to retreive all children */
		$children = $conn->query("SELECT * FROM keywords WHERE parent_id=$row[id]");
		return $children;
	}

	static function GetId($name)
	{
		$conn = GetConnection();
		/* note: NAME has UNIQUE constraint so we know 1 row is returned 	 */
		$results = $conn->query("SELECT * FROM keywords WHERE name='$name'");
		$error = $conn->error;
		return  $error != '' ? array('Server Error' => $error) : $results->fetch_assoc();  
	}
	static function Insert($row)
	{
		$conn = GetConnection();
		$row2 = EscapeRow($row, $conn);		
		$sql = 	"INSERT INTO keywords (name,parent_id)"
			.	"Values ('$row2[name]',$row2[parent_id]) ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
	}
	
	static function Update($row)
	{
		$conn = GetConnection();
		$row2 = EscapeRow($row, $conn);		
		$sql = 	"UPDATE keywords "
			.	"Set name='$row2[name]',parent_id=$row2[parent_id] "
			.	"WHERE id=$row2[id] ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
	}
	
	static function Delete($id)
	{
		$conn = GetConnection();
		$sql = 	"DELETE FROM keywords "
			.	"WHERE id=$id ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
		
	}
	static function Validate($row)
	{
		$results = array();
		if(empty($row['name'])) $results['name'] = 'Name is required';		
		
		return count($results) > 0 ? $results : true;
	}
	
	
}
?>

